<template>
    <div class="login" id="loginBg">
        <div class="loginCenter">
            <div class="login-head" style="margin-top: 0px">
                <div class="LogoImg1"><img :src="loginImg" /></div>
                <div class="LogoImg" style="font-size: 35px;color: rgb(255,255,255)">{{systemSrvName}}</div>
            </div>
          <div style="height: 100px">

          </div>
            <div class="login-form" :style="authType!== 'all'?'padding-top: 52px !important;':''">
              <div class="login-tab" v-if="authType=== 'all'">
                <ul>
                  <li @click="changeTab('1')" :class="currentTabName ==='1'?'curTab':''">密码登录</li>
                  <li @click="changeTab('2')" :class="currentTabName ==='2'?'curTab':''">UKey登录</li>
                </ul>
              </div>
              <a-form :form="form" v-if="currentTabName ==='1'">
                    <div style="display: block; opacity: 0; width: 0; height: 0; overflow: hidden">
                        <a-input type="text" name="username" autocomplete="off"></a-input>
                        <a-input type="password" name="password" autocomplete="off"></a-input>
                    </div>
                  <a-form-item style="margin-top:40px">
                    <a-input name="a" type="password" placeholder="密码"
                             style="position: fixed; bottom: -99999px"></a-input>
                    <a-input
                      :disabled="btnLoading" ref="refocus"
                      placeholder="请输入用户名"
                      size="large"
                      autocomplete="off"
                      v-decorator="[
                                'userName',
                                {
                                    rules: [{ required: true, message: '请输入用户名' }],
                                    getValueFromEvent: event => {
                                        return this.verify.formalSpace(event)
                                    }
                                }
                            ]"
                    >
                      <em slot="prefix" class="coin name"/>
                    </a-input>
                  </a-form-item>
                  <a-form-item>
                    <a-input
                      :disabled="btnLoading"
                      type="password"
                      size="large"
                      placeholder="请输入密码"
                      @pressEnter="allSubmit"
                      autocomplete="off"
                      style="color: #1f2f40;-webkit-text-security:disc; text-security:disc;ime-mode: disabled;"
                      @focus="changePwd"
                      @blur="changePwd"
                      @change="changePwd"
                      v-decorator="[
                                'password',
                                {
                                    rules: [{ required: true, message: '请输入密码' }],
                                    getValueFromEvent: event => {
                                        return this.verify.formalSpace(event)
                                    }
                                }
                            ]"
                    >
                      <em slot="prefix" class="coin msg"/>
                    </a-input>
                  </a-form-item>
                </a-form>
              <a-form :form="form" v-if="currentTabName ==='2'">
                <div style="display: block; opacity: 0; width: 0; height: 0; overflow: hidden">
                  <a-input type="text" name="username" autocomplete="off"></a-input>
                  <a-input type="password" name="password" autocomplete="off"></a-input>
                </div>
                <a-form-item style="margin-top: 40px">
                  <a-input name="a" type="password" placeholder="密码"
                           style="position: fixed; bottom: -99999px"></a-input>
                  <a-input
                    v-model="baseForm.userName"
                    placeholder="设备用户名"
                    size="large"
                    autocomplete="off"
                    disabled
                  >
                    <em slot="prefix" class="coin uukey" />
                  </a-input>
                </a-form-item>
                <a-form-item>
                  <a-input
                    :disabled="btnLoading"
                    size="large"
                    placeholder="请输入PIN码"
                    @pressEnter="submitUKeyLogon"
                    autocomplete="off"
                    style="color: #1f2f40;-webkit-text-security:disc; text-security:disc;ime-mode: disabled;"
                    type="password" ref="refocus1" v-model="baseForm.passwd"
                    @change="encodePsw"
                  >
                    <em slot="prefix" class="coin msg"/>
                  </a-input>
                </a-form-item>
              </a-form>
                <a-form-item  style="margin-top:32px !important;">
                    <div class="error" v-if="msg !== ''">{{ msg }}</div>
                    <a-button html-type="submit" :disabled="btnLoading" @click="allSubmit" size="large"
                              class="loginBtn">登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录
                    </a-button>
                </a-form-item>
                <!-- 登录页驱动下载处理 -->
                <div>
                  <span v-if="showLoadUrl && currentTabName === '2'" class="showDownStyle"
                        :style="authType!== 'all'?'top:310px;':'top:335px;'"
                        @click="downLoadUkeyDevice()">下载UKey实体鉴别客户端</span>
                    <iframe id="ifile" title="下载UKey实体鉴别客户端" style="display: none"></iframe>
                </div>
                <div class="copyRight"><a>© {{copyRight}} </a></div>
            </div>
            <div class="login-formt">
                <div class="showBox"></div>
                <div class="loginBtn">登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录</div>
                <div class="copyRight"><a>© {{copyRight}} </a></div>
            </div>
        </div>
      <set-role ref="setRole" @getSystemSrvNameActt="getSystemSrvNameActt"/>
    </div>
</template>
<script>
    import verify from 'libs/verify'
    import * as State from '@/libs/baseStateConts';
    import {mapActions, mapState} from 'vuex'
    import store from '@/commontToken'
    import setRole from 'module/setRole.vue'

    const sm2 = require ('sm-crypto').sm2;
  const sm3 = require ('sm-crypto').sm3;
  const Base64 = require ('js-base64').Base64;
  export default {
      components: {
          setRole
      },
      data() {
          return {
              baseForm: {
                  userName: '',
                  password: '',
                  user: '',
                  passwd: '',
                  deviceId: '',
                  deviceId2: '',
                  passwd2: '',
                  passwd3: ''
              },
              verify,
              btnLoading: false,
              form: this.$form.createForm(this),
              msg: '',
              title: '',
              pwdType: 'password', // 密码框显示密码的控制
              eyeStatusName: 'eye-disabled', // 密码框显示密码的图标展示控制
              showLoadUrl: false, //显示UKEY驱动软件下载链接控制
              enabledPsw: false,
              scanUKeyTimer: -1,
              btnDisabled: false,
              systemSrvName: '管理系统',
              copyRight: 'AASTU',
              subMicro: '',
              loginImg: '',
              currentTabName: '1',
              isInitialized: false,
              isInitializedKey: false
          }
      },
      computed: {
          ...mapState({
              qsBackData: state => state.common.qsBackData,
              authType: state => state.common.authType,
          })
      },
      watch: {
          qsBackData: {
              handler(val) {
                  if (this.currentTabName === '2') {
                      let optWeb = val.optWeb
                      if (optWeb === 114) {
                          this.ukeyLogin()
                      } else if (optWeb === 6) {
                          this.getChallengeRandom()
                      }else if (optWeb === 7) {
                          this.$root.qsLib.checkAuthUKey (this.baseForm.deviceId,this.baseForm.passwd)
                      } else if (optWeb === 9) {
                          this.msg = this.qsBackData.message
                      } else if (optWeb === 8) {
                          this.showLoadUrl = true
                      } else if (optWeb === 2) {
                          this.startScanTimer()
                      } else if (optWeb === 1) {
                          this.showLoadUrl = false
                          if (this.qsBackData.data.length === 1) {
                              this.baseForm.deviceId = this.qsBackData.data[0].device_id;
                              if (this.baseForm.userName === '') {
                                  this.msg = ''
                                  this.baseForm.passwd = ''
                                  this.getUkeyUsername()
                              }
                          } else {
                              this.baseForm.userName = ''
                              this.baseForm.passwd = ''
                              this.msg = '存在多个安全UKey'
                          }
                      } else if (optWeb === 4098) {
                          this.showLoadUrl = false
                          this.baseForm.deviceId = ''
                          this.baseForm.userName = ''
                          this.msg = val.message
                      }
                  }
              },
              deep: true,
              immediate: false
          }
      },
      methods: {
          ...mapActions('global', ['setGlobalState']),
          changeUsername(sendData) {
              store.setGlobalState({
                  user: {name: '李四' + Math.round(Math.random() * 100)},
                  styleObj: sendData
              })
          },
          /**
           * Function    : changeTab
           * Description : 切换tab页面
           * Input       : name  tab中指定名称
           * Return      : none
           */
          changeTab(name) {
              let _this = this
              _this.form.resetFields()
              this.currentTabName = name
              this.msg = ''
              let focusIput = 'refocus'
              this.clearScanTimer()
              if (_this.currentTabName === '2') {
                  focusIput = 'refocus1'
                  _this.$store.dispatch('setGlobalUserKey', {
                      'code': 0,
                      'optWeb': 0,
                      'message': ''
                  })
                  _this.startScanTimer();

              }
              setTimeout(function () {
                  _this.$refs[focusIput].focus()
              }, 200)
          },
          loadSysStyleInfo() {
              let _this = this
              this.$otherGetParams('api/info/loadSysStyleInfo', {}, 'sysstyle').then(res => {
                  if (res.code === 0) {
                      let data = res.data
                      data.backgroundImage = 'data:image/png;base64,' + res.data.backgroundImage
                      data.logonLogo = 'data:image/png;base64,' + res.data.logonLogo
                      data.headerLogo = 'data:image/png;base64,' + res.data.headerLogo
                      sessionStorage.setItem('companyName', data.companyName)
                      sessionStorage.setItem('companyShortName', data.companyShortName)
                      sessionStorage.setItem('copyRight', data.copyRight)
                      sessionStorage.setItem('pageStyle', data.pageStyle)
                      localStorage.setItem('backgroundImage', data.backgroundImage)
                      localStorage.setItem('logonLogo', data.logonLogo)
                      localStorage.setItem('headerLogo', data.headerLogo)
                      _this.systemSrvName = data.companyName
                      _this.copyRight = data.copyRight
                      _this.loginImg = data.logonLogo
                      document.getElementById('loginBg').style.backgroundImage = 'url(' + data.backgroundImage + ')'
                      let sendData = {
                          headerLogo: data.headerLogo,
                          companyShortName: data.companyShortName,
                          companyName: data.companyName,
                          pageStyle: data.pageStyle,
                          copyRight: data.copyRight
                      }
                      _this.$store.dispatch('setStyleObj', sendData)
                      _this.changeUsername(sendData)
                  } else {
                      _this.$message.error(res.message)
                  }
              })
          },
            allSubmit(){
                if(this.currentTabName === '2'){
                    this.submitUKeyLogon()
                }else{
                    this.handleSubmit()
                }
            },
            changePwd(){
                this.msg = ''
            },
            /**
             * Function    : init
             * Description : 初始化清空sessionStorage和localStorage数据
             * Input       : none
             * Return      : none
             */
            init () {
              this.subMicro = sessionStorage.getItem('subMicro')
                //获取当前系统名称
                if (sessionStorage.getItem ('interceptorMsg') !== null) {
                    this.msg = sessionStorage.getItem ('interceptorMsg')
                    sessionStorage.removeItem ('interceptorMsg')
                    sessionStorage.clear ()
                } else {
                    sessionStorage.clear ()
                }
                if (localStorage.getItem ('interceptorMsg') !== null) {
                    this.$message.success (localStorage.getItem ('interceptorMsg'),10)
                    localStorage.clear ()
                } else {
                    localStorage.clear ()
                }
               sessionStorage.setItem('subMicro',this.subMicro)
                /*let _this = this;
                //获取当前系统名称
                _this.$store.dispatch('loadSystemSrvNameAct').then(response => {
                    if (response.code === 0) {
                        _this.initSetLoginType (response.data);
                    } else {
                        _this.msg = response.message;
                    }
                }).catch(e=>{
                    _this.msg = "当前登录页面失效，稍后将重新加载...";
                });*/
            },
            getSystemSrvNameActt(){
                let _this = this;
                _this.$store.dispatch ('loadSystemSrvNameAct')
                _this.loadSysStyleInfo();
            },


            /**
             * Function    : initSetLoginType
             * Description : 初始化设置登录类型
             * Input       : None
             * Return      : None
             */
            /*initSetLoginType (respData) {
                let _this = this;
                //获取系统认证登录方式
                if (respData.currentLoginType === 'UKEY') {
                    _this.isUKeyLogin = true;
                    //扫描外接安全U盾
                    _this.startScanTimer();
                } else if (respData.currentLoginType === 'PSW') {
                    _this.isUKeyLogin = false
                }
                sessionStorage.setItem('isUKeyLogin', _this.isUKeyLogin);
            },*/

            /**
             * Function    : clearScanTimer
             * Description : 开启扫描UKey设备定时器
             * Input       : None
             * Return      : None
             */
            startScanTimer () {
                let _this = this;
                _this.clearScanTimer ();
                if (_this.scanUKeyTimer !== -1) {
                    return
                }
                _this.$root.qsLib.getDeviceInfo()  //获取设备信息
                //_this.baseForm.deviceId =  _this.$root.qsLib.deviceObj.deviceId;
                _this.baseForm.userName = '';
                _this.baseForm.passwd = '';
                //开启扫描外接密钥存储设备定时器
                _this.scanUKeyTimer = setInterval (function () {
                  _this.$root.qsLib.getDeviceInfo()
                }, 1000 *1)
            },

            /**
             * Function    : clearScanTimer
             * Description : 关闭扫描UKey设备定时器
             * Input       : None
             * Return      : None
             */
            clearScanTimer () {
                let _this = this;
                //关闭定时器
                if (_this.scanUKeyTimer === -1) {
                    return
                }
                clearInterval (_this.scanUKeyTimer);
                _this.scanUKeyTimer = -1
            },

            /**
             * Function    : downLoadUkeyDevice
             * Description : 下载U盾认证登录驱动
             * Input       : None
             * Return      : None
             */
            downLoadUkeyDevice () {
                document.getElementById ('ifile').src = '/auth/downloadUkeyClient';
            },

            /**
             * Function    : submitUKeyLogon
             * Description : UKey系统认证登录
             * Input       : None
             * Return      : None
             */
            submitUKeyLogon () {
                let _this = this;
                let params = {};
                if(_this.msg !== ''){
                    return;
                }
                _this.msg = '';
                /**
                 * 设备PIN码认证登录
                 */
                let password = _this.baseForm.passwd;
                let deviceId = _this.baseForm.deviceId;
                if (deviceId.length === 0) {
                    _this.msg = '请插入安全UKey';
                    return;
                }
                if (password.length === 0) {
                    _this.msg = 'PIN码不能为空';
                    return;
                }
               //_this.$root.qsLib.checkAuthUKey (_this.baseForm.deviceId,_this.baseForm.passwd)
                _this.$root.qsLib.setInitParams (this.baseForm.deviceId)
            },

            encodePsw() {
                this.encodedPsw = encodeURIComponent(this.baseForm.passwd)
            },
            /**
             * Function    : loadSystemInfoForUser
             * Description : 加载登录用户的系统资源信息
             * Input       : none
             * Return      : none
             */
            getNacosServices() {
                let _this = this
                this.$get('api/getSysServices').then(res => {
                    if (res.code === 0) {
                        let newList = res.data
                        for (let i = 0; i < newList.length - 1; i++) {
                            for (let j = i + 1; j < newList.length; j++) {
                                if (newList[i].serverCode === newList[j].serverCode) {
                                    newList.splice(j, 1)
                                    j--
                                }
                            }
                        }
                        sessionStorage.setItem('nacosService', JSON.stringify(newList))
                    } else {
                        _this.btnLoading = false
                        _this.$message.error(res.message)
                    }
                }).catch(e => {
                    this.btnLoading = false
                    this.$message.error('后台系统异常')
                })
            },
            loadSystemInfoForUser() {
                let _this = this
                this.$get('api/getSysServices').then(res => {
                    if (res.code === 0) {
                        let newList = res.data
                        for (let i = 0; i < newList.length - 1; i++) {
                            for (let j = i + 1; j < newList.length; j++) {
                                if (newList[i].serverCode === newList[j].serverCode) {
                                    newList.splice(j, 1)
                                    j--
                                }
                            }
                        }
                        sessionStorage.setItem('nacosService', JSON.stringify(newList))
                        let target = newList.filter(item => item.serverCode === 'qrngser')
                        if (target.length > 0) {
                            _this.$otherGetParams('getSystemConfig', {}, 'qrngser').then(ress => {
                                if (ress.code === 0) {
                                    if (ress.data.deviceId !== '' && ress.data.deviceId !== null && ress.data.deviceId !== undefined) {
                                          _this.getUserPermissions()
                                          sessionStorage.setItem('linkCenterFlag',ress.data.linkCenterFlag)
                                    } else {
                                        _this.$refs.setRole.showModal()
                                        _this.$nextTick(() => {
                                            _this.form.setFieldsValue({password: ''})
                                        })
                                        _this.btnLoading = false
                                    }
                                } else {
                                    _this.$nextTick(() => {
                                        _this.form.setFieldsValue({password: ''})
                                    })
                                    _this.btnLoading = false
                                }
                            }).catch(e => {
                                _this.btnLoading = false
                                this.$message.error('后台系统异常')
                            })
                        } else {
                            _this.getUserPermissions()
                        }

                    } else {
                        _this.btnLoading = false
                        _this.$message.error(res.message)
                    }
                }).catch(e => {
                    this.btnLoading = false
                    this.$message.error('后台系统异常')
                })
            },

          getSrceenObj(){
              let _this =this
              this.$otherGetParams ('api/sysconfig/getSysConfigByCode', {code: '10000004',serverCode:'micrApp'},'sysconf').then (res => {
                  if (res.code === 0) {
                      if(JSON.stringify(res.data) !== '{}'){
                          _this.handleStatsFillScreen = res.data.paramValue
                      }else{
                          _this.handleStatsFillScreen = ''
                      }
                  } else {
                      _this.$message.error (res.data.message)
                  }
              })
          },

            getUserPermissions(){
                let roleIds = JSON.parse(sessionStorage.getItem('roleIds'))
                let _this =this
                _this.clearScanTimer ();
                if(roleIds.length>0){
                    let role_id = roleIds[0]
                    /*if(role_id=== 'ROLE_f70ec3e19e1e422a8e5d6d00c4eb1863'  || role_id=== 'ROLE_aec796fdc7295441ac4c138c061c4af3' || role_id=== 'ROLE_anonymous'){
                        this.$router.push({
                            path: '/micrApp/auth1.0/userInfo'
                        }, onComplete => {
                        }, onAbort => {
                        })
                    }else*/ if(role_id=== 'ROLE_5bd8be720481475faf60af85734d87fd'){
                        this.$router.push({
                            path: '/micrApp/audit1.0/auditlogs'
                        }, onComplete => {
                        }, onAbort => {
                        })
                    }else{
                        this.$otherGetParams ('api/sysconfig/getSysConfigByCode', {code: '10000004',serverCode:'micrApp'},'sysconf').then (res => {
                            if (res.code === 0) {
                                _this.$router.push({
                                    path: res.data.paramValue
                                }, onComplete => {
                                }, onAbort => {
                                })
                            } else {
                                _this.btnLoading = false
                                _this.$message.error (res.data.message)
                            }
                        }).catch(e => {
                            this.btnLoading = false
                            this.$message.error('后台系统异常')
                        })
                    }
                }
                this.$store.dispatch('getUserPermissions').then(resp => {
                    this.btnDisabled = false;
                    if (resp.code === 0) {
                        sessionStorage.setItem('permissions', JSON.stringify(resp.data || '[]'))
                    } else {
                        this.msg = resp.message
                    }
                }).catch(e => {
                    this.btnLoading = false
                    this.$message.error('后台系统异常')
                })
            },

            /**
             * Function    : handleSubmit
             * Description : 登录提交
             * Input       : none
             * Return      : none
             */
            handleSubmit () {
                this.msg = ''
                this.btnLoading = true
                this.btnDisabled = true;
                this.form.validateFields (( err, value ) => {
                    if (!err) {
                        this.baseForm.userName = value.userName
                        this.baseForm.password = sm3(value.password)
                        let _this =this
                        let formData = new FormData ()
                        formData.append ('username', value.userName)
                        formData.append ('password',sm3(value.password))
                        _this.$uploadPost ('api/login', formData).then (response => {
                            if (response.code === 0) {
                                this.msg = ''
                                let token = response.data.token
                                sessionStorage.setItem ('user', this.baseForm.userName)
                                sessionStorage.setItem ('token', token)
                                sessionStorage.setItem ('loginName', response.data.name)
                                sessionStorage.setItem ('loginUserId', response.data.id)
                                sessionStorage.setItem ('title', this.systemSrvName)
                                sessionStorage.setItem ('curLoginType', 'PSW')
                                sessionStorage.setItem ('roleIds', JSON.stringify(response.data.roleIds))
                                sessionStorage.setItem ('initUkey',response.data.initUkey)
                                //sessionStorage.setItem ('initUkey',false)
                                if (token === '') {
                                    sessionStorage.setItem('defaultPsw', '0');
                                    sessionStorage.setItem('permissions', JSON.stringify('[]'));
                                    this.$router.push({
                                        name: 'userInfo'
                                    });
                                } else {
                                    sessionStorage.setItem('defaultPsw', response.data.defaultPsw);
                                    this.loadSystemInfoForUser();
                                }
                            } else {
                                this.msg = response.message
                                this.btnLoading = false
                            }
                        }).catch (e => {
                            this.btnLoading = false
                            this.$message.error ('后台系统异常')
                        })
                    } else {
                        setTimeout (() => {
                            this.btnLoading = false
                        }, 600)
                    }
                })
            },
             getChallengeRandom(){
               let _this = this
               _this.$get ('api/getChallengeRandom',{username:_this.baseForm.userName}).then (res => {
                 if (res.code === 0) {
                   _this.$root.qsLib.getSignKeyFun (res.data)
                 }else {
                   _this.$message.error (res.message)
                 }
               }).catch(e => {
                   this.btnLoading = false
                   this.$message.error('后台系统异常')
               })
             },

          ukeyLogin(){
            let _this = this
            _this.$post ('api/ukeyLogin',{username:_this.baseForm.userName,sign:_this.$root.qsLib.userKey.signData}).then (res => {
              if (res.code === 0) {
                this.msg = ''
                let token = res.data.token
                sessionStorage.setItem ('user', this.baseForm.userName)
                sessionStorage.setItem ('deviceId',  this.baseForm.deviceId)
                sessionStorage.setItem ('token', token)
                sessionStorage.setItem ('title', this.systemSrvName)
                sessionStorage.setItem ('curLoginType', 'UKEY')
                  sessionStorage.setItem ('roleIds', JSON.stringify(res.data.roleIds))
                if (token === '') {
                  this.getNacosServices()
                  sessionStorage.setItem('defaultPsw', '0');
                  sessionStorage.setItem('permissions', JSON.stringify('[]'));
                  this.$router.push({
                     path: '/micrApp/auth1.0/userInfo'
                  });
                } else {
                  sessionStorage.setItem('defaultPsw', res.data.defaultPsw);
                  this.loadSystemInfoForUser();
                }
              }else {
                  _this.baseForm.passwd = ''
                  _this.btnLoading = false
                  _this.$message.error (res.message)
                  _this.startScanTimer();
              }
            }).catch(e => {
                this.btnLoading = false
                this.$message.error('后台系统异常')
            })
          },

          getUkeyUsername() {
              let _this = this
              this.$get('api/sysuser/getUkeyUsername', {deviceId: _this.baseForm.deviceId}).then(res => {
                  if (res.code === 0) {
                      _this.baseForm.userName = res.data
                  } else {
                      _this.baseForm.userName = _this.baseForm.deviceId
                      _this.msg = '请插入有效UKey'
                  }
              })
          },
            unwatch(){
                this.$watch('qsBackData',function (val,oldVal) {
                    console.log('取消监控')
                    console.log(val)
                    console.log(oldVal)
                })
            }
        },
        created () {
            this.loadSysStyleInfo();
            this.init ()
            let _this = this
            let focusIput = 'refocus'
            if(this.authType === 'ukey'){
                this.currentTabName = '2'
                focusIput = 'refocus1'
                _this.$store.dispatch('setGlobalUserKey', {
                    'code': 0,
                    'optWeb': 0,
                    'message': ''
                })
                _this.startScanTimer();
            }
            setTimeout(function () {
                _this.$refs[focusIput].focus()
            }, 200)

        },
        /**
         * 组件销毁前处理
         */
        beforeDestroy () {
            this.clearScanTimer ()
            this.unwatch()
        }
    }
</script>
<style lang="less">
    @import '~assets/login.less';
    .showDownStyle{
        font-size: 14px;color: #06f130;cursor: pointer;position:absolute; left:45px; top:335px;margin-left: 3px;
    }
</style>
